package com.example.homeworkdev.pages;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.homeworkdev.Dao.UserDao;
import com.example.homeworkdev.R;
import com.example.homeworkdev.entity.User;

public class RegisterActivity extends AppCompatActivity {
    private RelativeLayout rootLayout;
    private AnimationDrawable backgroundAnimation;
    private EditText etPhone, etVerifyCode, etPassword, etConfirmPwd;
    private Button btnGetCode, btnRegister;
    private ImageView ivShowPwd, ivShowConfirmPwd;
    private CheckBox cbAgreement;
    private CountDownTimer countDownTimer;

    private UserDao userDao = new UserDao(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // 初始化视图
        rootLayout = findViewById(R.id.register_layout);
        etPhone = findViewById(R.id.et_phone);
        etVerifyCode = findViewById(R.id.et_verify_code);
        etPassword = findViewById(R.id.et_password);
        etConfirmPwd = findViewById(R.id.et_confirm_pwd);
        btnGetCode = findViewById(R.id.btn_get_code);
        btnRegister = findViewById(R.id.btn_register);
        ivShowPwd = findViewById(R.id.iv_show_pwd);
        ivShowConfirmPwd = findViewById(R.id.iv_show_confirm_pwd);
        cbAgreement = findViewById(R.id.cb_agreement);

        // 启动背景动画
        backgroundAnimation = (AnimationDrawable) rootLayout.getBackground();
        backgroundAnimation.start();

        // 返回按钮
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 获取验证码按钮
        btnGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = etPhone.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(RegisterActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!phone.matches("^1[3-9]\\d{9}$")) {
                    Toast.makeText(RegisterActivity.this, "请输入有效的手机号", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 开始倒计时
                startCountdown();

                // 实际开发中这里调用发送验证码的API
                Toast.makeText(RegisterActivity.this, "验证码已发送，请注意查收", Toast.LENGTH_SHORT).show();
            }
        });

        // 显示/隐藏密码
        ivShowPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                togglePasswordVisibility(etPassword, ivShowPwd);
            }
        });

        ivShowConfirmPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                togglePasswordVisibility(etConfirmPwd, ivShowConfirmPwd);
            }
        });

        // 注册按钮
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                register();
            }
        });

        // 用户协议和隐私政策点击事件
        findViewById(R.id.tv_user_agreement).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAgreement("用户协议");
            }
        });

        findViewById(R.id.tv_privacy_policy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAgreement("隐私政策");
            }
        });
    }

    // 切换密码可见性
    private void togglePasswordVisibility(EditText editText, ImageView imageView) {
        boolean isVisible = editText.getInputType() != (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        editText.setInputType(isVisible ?
                InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD :
                InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        editText.setSelection(editText.getText().length());
        imageView.setImageResource(isVisible ? R.drawable.ic_eye_hide : R.drawable.ic_eye_show);
    }

    // 开始倒计时
    private void startCountdown() {
        btnGetCode.setEnabled(false);
        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                btnGetCode.setText("重新发送(" + millisUntilFinished / 1000 + "s)");
            }

            @Override
            public void onFinish() {
                btnGetCode.setEnabled(true);
                btnGetCode.setText("获取验证码");
            }
        }.start();
    }

    // 注册逻辑
    private void register() {
        String phone = etPhone.getText().toString().trim();
        String verifyCode = etVerifyCode.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String confirmPwd = etConfirmPwd.getText().toString().trim();

        // 验证输入
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!phone.matches("^1[3-9]\\d{9}$")) {
            Toast.makeText(this, "请输入有效的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(verifyCode)) {
            Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请设置密码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (password.length() < 6) {
            Toast.makeText(this, "密码长度至少6位", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!password.equals(confirmPwd)) {
            Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!cbAgreement.isChecked()) {
            Toast.makeText(this, "请同意用户协议和隐私政策", Toast.LENGTH_SHORT).show();
            return;
        }

        // 显示加载中
        btnRegister.setEnabled(false);
        btnRegister.setText("注册中...");

        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            // 延迟2秒执行任务
            // 注册用户
            boolean checkResult = userDao.checkPhoneExists(phone);
            if(checkResult){
                btnRegister.setEnabled(true);
                btnRegister.setText("立即注册");
                Toast.makeText(RegisterActivity.this, "该手机号已被注册", Toast.LENGTH_SHORT).show();
            }else {
                userDao.registerUser(phone,password);
                // 注册成功，返回登录页面
                Toast.makeText(RegisterActivity.this, "注册成功，请登录", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }

        }, 2000);

    }

    // 显示协议内容（实际开发中可跳转到WebView页面）
    private void showAgreement(String title) {
        Toast.makeText(this, "显示" + title, Toast.LENGTH_SHORT).show();
        // 实际开发中可跳转到WebView页面加载协议内容
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (backgroundAnimation != null && backgroundAnimation.isRunning()) {
            backgroundAnimation.stop();
        }
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (backgroundAnimation != null && !backgroundAnimation.isRunning()) {
            backgroundAnimation.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    //跳转到登录页面的方法
    public void navigateToLogin(View view) {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }
}
